//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.ScientificWorkflow.ManagementStudioModels
{
    using System;
    using System.Windows;
    using System.Windows.Media.Imaging;
    using Microsoft.Research.ScientificWorkflow.TridentUtilities;
    using SR = Microsoft.Research.DataLayer;
    using System.Globalization;

    /// <summary>
    /// Model for data reference store.
    /// </summary>
    public class DataReferenceStoreModel : BaseRegMgrModel
    {
        /// <summary>
        /// Is the model is complete?
        /// </summary>
        private bool completeReferenceStoreModel;

        /// <summary>
        /// Is new.
        /// </summary>
        private bool isNew;

        /// <summary>
        /// Can be deleted?
        /// </summary>
        private bool canDeletable;

        /// <summary>
        /// Display ID.
        /// </summary>
        private Guid displayId;

        /// <summary>
        /// Parameters.
        /// </summary>
        private string parameters;

        /// <summary>
        /// Gets or sets a value indicating whether [complete reference provider model].
        /// </summary>
        /// <value>
        /// 	<c>true</c> if [complete reference provider model]; otherwise, <c>false</c>.
        /// </value>
        public bool CompleteReferenceStoreModel
        {
            get
            {
                return this.completeReferenceStoreModel;
            }
            set
            {
                this.completeReferenceStoreModel = value;
                this.RaisePropertyChanged("CompleteReferenceStoreModel");
            }
        }

        /// <summary>
        /// Gets or sets the external registry connection parameters.
        /// </summary>
        /// <value>The parameters.</value>
        public string Parameters
        {
            get
            {
                return this.parameters;
            }
            set
            {
                this.parameters = value;
                this.RaisePropertyChanged("Parameters");
            }
        }

        /// <summary>
        /// Gets or sets the id.
        /// </summary>
        /// <value>The id.</value>
        public override Guid Id
        {
            get
            {
                return base.Id;
            }
            set
            {
                base.Id = value;
                this.DisplayId = value;
                this.IsNew = (base.Id == null) || (base.Id != null && base.Id.Equals(Guid.Empty));
                this.RaisePropertyChanged("Id");
            }
        }

        /// <summary>
        /// Gets or sets the display id.
        /// </summary>
        /// <value>The display id.</value>
        public Guid DisplayId
        {
            get
            {
                if (this.displayId.Equals(Guid.Empty))
                {
                    return (Guid)DependencyProperty.UnsetValue;
                }

                return this.displayId;
            }
            set
            {
                this.displayId = value;
                this.RaisePropertyChanged("DisplayId");
            }
        }

        /// <summary>
        /// Gets a value indicating whether this instance is new.
        /// </summary>
        /// <value><c>true</c> if this instance is new; otherwise, <c>false</c>.</value>
        public bool IsNew
        {
            get
            {
                return this.isNew;
            }
            set
            {
                this.isNew = value;
                this.CanDelete = !value;
                this.RaisePropertyChanged("IsNew");
            }
        }

        /// <summary>
        /// Gets or sets a value indicating whether this instance can be deleted.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance can delete; otherwise, <c>false</c>.
        /// </value>
        public bool CanDelete
        {
            get
            {
                return this.canDeletable;
            }
            set
            {
                this.canDeletable = value;
                this.RaisePropertyChanged("CanDelete");
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DataReferenceStoreModel"/> class.
        /// </summary>
        /// <param name="store">The store.</param>
        public DataReferenceStoreModel(string name, DataReferenceProviderModel parent)
        {
            this.Id = Guid.Empty;
            this.Name = name;
            this.Description = string.Empty;

            this.Parent = parent;

            this.ItemIcon = CreateImage("pack://Application:,,,/Microsoft.Research.ScientificWorkflow.TridentUtilities;component/Images/ManagementStudio/AdvancedConnectionsmall.png");

            this.CompleteReferenceStoreModel = true;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DataReferenceStoreModel"/> class.
        /// </summary>
        /// <param name="store">The store.</param>
        /// <param name="parent">The parent.</param>
        public DataReferenceStoreModel(SR.DataReferenceStore store, DataReferenceProviderModel parent)
        {
            if (store != null)
            {
                this.Update(store, parent);

                this.CompleteReferenceStoreModel = true;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DataReferenceStoreModel"/> class.
        /// </summary>
        /// <param name="store">The store.</param>
        public DataReferenceStoreModel(DataReferenceStoreModel store)
        {
            if (store != null)
            {
                this.Update(store);

                this.CompleteReferenceStoreModel = true;
            }
        }

        /// <summary>
        /// Creates the clone.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns></returns>
        public static DataReferenceStoreModel CreateClone(DataReferenceStoreModel model)
        {
            DataReferenceStoreModel clonedModel = null;
            if (null != model)
            {
                clonedModel = new DataReferenceStoreModel(model);
            }

            return clonedModel;
        }

        /// <summary>
        /// Updates the model with the specified provider.
        /// </summary>
        /// <param name="store">The store.</param>
        /// <param name="parent">The parent.</param>
        public void Update(SR.DataReferenceStore store, BaseRegMgrModel parent)
        {
            if (store != null)
            {
                this.Id = ((SR.IObject)store).ID;
                this.Name = store.Name;
                this.Description = store.Description;

                this.Parameters = store.DataProviderParameters;
                this.Parent = parent;

                this.CreatedBy = store.Created.User;
                this.CreatedDate = store.Created.When;
                this.LastModifiedTime = store.Updated.When;
                this.LastModifiedBy = store.Updated.User;

                this.ItemIcon = CreateImage("pack://Application:,,,/Microsoft.Research.ScientificWorkflow.TridentUtilities;component/Images/ManagementStudio/AdvancedConnectionsmall.png");
            }
        }

        /// <summary>
        /// Creates the image.
        /// </summary>
        /// <param name="imagePath">The image path.</param>
        /// <returns></returns>
        private BitmapImage CreateImage(string imagePath)
        {
            BitmapImage image = null;
            try
            {
                image = new BitmapImage(new Uri(imagePath, UriKind.Absolute));
            }
            catch (Exception ex)
            {
                TridentErrorHandler.HandleUIException(ex);
            }

            return image;
        }

        /// <summary>
        /// Gets the temp name for the store.
        /// </summary>
        /// <param name="parent">The parent.</param>
        /// <returns></returns>
        public static string GetStoreTempName(BaseRegMgrModel parent)
        {
            string tempName = "Store";

            int latestId = 0;

            if (parent != null)
            {
                foreach (BaseRegMgrModel model in parent.Children)
                {
                    if (model.Name.StartsWith(tempName, StringComparison.OrdinalIgnoreCase))
                    {
                        int id = 0;
                        if (int.TryParse(model.Name.Replace(tempName, string.Empty), out id))
                        {
                            latestId = id > latestId ? id : latestId;
                        }
                    }
                }
                latestId++;
            }

            return string.Format(CultureInfo.CurrentCulture, "{0}{1}", tempName, latestId.ToString(CultureInfo.CurrentCulture));
        }

        /// <summary>
        /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
        /// <returns>
        /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">
        /// The <paramref name="obj"/> parameter is null.
        /// </exception>
        public override bool Equals(object obj)
        {
            bool equal = false;
            DataReferenceStoreModel equateParam = obj as DataReferenceStoreModel;
            if (equateParam != null &&
                equateParam.Id.Equals(this.Id) &&
                DataReferenceStoreModel.CheckEquality(equateParam.Name, this.Name) &&
                DataReferenceStoreModel.CheckEquality(equateParam.Description, this.Description) &&
                DataReferenceStoreModel.CheckEquality(equateParam.Parameters, this.Parameters) &&
                equateParam.LastModifiedTime.Equals(this.LastModifiedTime) &&
                ((equateParam.Parent == null && this.Parent == null) ||
                (equateParam.Parent != null && this.Parent != null && equateParam.Parent.Id.Equals(this.Parent.Id))))
            {
                equal = true;
            }

            return equal;
        }

        /// <summary>
        /// Serves as a hash function for a particular type.
        /// </summary>
        /// <returns>
        /// A hash code for the current <see cref="T:System.Object"/>.
        /// </returns>
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        /// <summary>
        /// Updates the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        public override void Update(BaseRegMgrModel model)
        {
            DataReferenceStoreModel store = model as DataReferenceStoreModel;
            if (store != null)
            {
                this.Id = store.Id;
                this.Name = store.Name;
                this.Description = store.Description;

                this.Parameters = store.Parameters;

                this.Parent = store.Parent;
                this.CreatedBy = store.CreatedBy;
                this.CreatedDate = store.CreatedDate;
                this.LastModifiedTime = store.LastModifiedTime;
                this.LastModifiedBy = store.LastModifiedBy;

                this.ItemIcon = CreateImage("pack://Application:,,,/Microsoft.Research.ScientificWorkflow.TridentUtilities;component/Images/ManagementStudio/AdvancedConnectionsmall.png");
            }
        }

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString()
        {
            return this.Name;
        }
    }
}
